# CSS Box Model

Box Model (opens new window) 模块描述了 margin (opens new window) 和 padding (opens new window) 属性,这些属性用于在 CSS 盒模型内部及周围创建间距。

Box Sizing (opens new window) 模块通过引入基于内容的 intrinsic (opens new window) 尺寸和基于上下文的 extrinsic (opens new window) 尺寸,扩展了 CSS 的尺寸属性。这使得 CSS 能够更轻松地描述那些适应自身内容或融入特定布局上下文的盒子。

# 一、尺寸

控制 Box 尺寸的属性有 width (opens new window)、height (opens new window)、min-width (opens new window)、min-height (opens new window)、max-width (opens new window) 和 max-height (opens new window)。

在 CSS 盒模型的默认定义里,对一个元素所设置的 width 与 height 只会应用到这个元素的内容区。

div {
  width: 100px;
  background-color: green;
}

如果 box-sizing (opens new window) 属性被设置为 border-box (opens new window),那么设置的边框和内边距的值是包含在 width 和 height 内的。

div {
  width: 100px;
  height: 100px;
  background-color: green;
  box-sizing: border-box;
  padding: 10px;
  border: 10px solid black;
}

如果需要根据内容长度,动态设置宽高时,可以使用 min-content (opens new window) 或 max-content (opens new window) 属性值。

对于文本内容而言,min-content 表示的是内容的最小宽度,会利用所有软换行的机会,使大小不会超过最长单词的宽度。

<p class="max-content">This is a long piece of text that might need different width settings.</p>
<p class="min-content">This is a long piece of text that might need different width settings.</p>
.max-content {
  width: max-content;
  border: 1px solid black;
}

.min-content {
  width: min-content;
  border: 1px solid black;
}